const express = require('express')
const mysql = require('mysql')
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456789',
  database: 'learner'
})
// title, pic_src, big_pic_src, summary, content, post_time, author, n_view
module.exports = function () {
  let router = express.Router()

  router.get('/', (req, res) => {
    db.query(`SELECT * FROM blog_table`, (err, blogs) => {
      if (err) {
        console.error(err)
        res.status(500).send('database error').end()
      } else {
        res.render('admin/blog.ejs', { blogs })
      }
    })
  })

  router.post('/', (req, res) => {
    let title = req.body.title
    let pic_src = req.body.pic_src
    let big_pic_src = req.body.big_pic_src
    let summary = req.body.summary
    let content = req.body.content
    let post_time = Date.parse(new Date()) / 1000
    let author = req.body.author
    let n_view = 0
    db.query(`INSERT INTO blog_table (title, pic_src, big_pic_src, summary, content, post_time, author, n_view) VALUE ('${title}', '${pic_src}', '${big_pic_src}', '${summary}', '${content}', '${post_time}', '${author}', '${n_view}')`, (err, data) => {
      if (err) {
        console.error(err)
        res.status(500).send('database error').end()
      } else {
        res.redirect('/admin/blog')
      }
    })
  })

  return router
}
